// ActionScript file
import Modules.Opportunity.OpportunityDetail;
import Modules.Windows.ValidationErrorWin;

import com.desidea.common.CommonClass;
import com.desidea.webservice.PartnerService;
import com.desidea.webservice.ProcessServiceRequestResultEvent;

import flash.display.DisplayObject;

import mx.controls.Alert;
import mx.events.CloseEvent;
import mx.managers.PopUpManager;
import mx.rpc.events.FaultEvent;
import mx.utils.StringUtil;
import mx.validators.Validator;


private var oppProdDetails:XML;
private var _key:String = "";
public var  _caller:DisplayObject;
public var _opportunityGUID:String;

public function get key():String{
	return _key;
}
public function set key(value:String):void{
	_key = value;
}

public function get caller():DisplayObject{
	return _caller;
}
public function set caller(value:DisplayObject):void{
	_caller = value;
}

public function get opportunityGUID():String{
	return _opportunityGUID;
}

public function set opportunityGUID(value:String):void{
	_opportunityGUID =  value;
}


private function windowCreated():void{
	this.loadData();
	this.cmbProductName.setFocus();
}

private function init():void{
}

private function onClick(mode:String):void{
	switch(mode){
		case "save":
			handleSave();
			break;
		case "cancel":
			handleCancel();
			break;
	}
}

private function handleCancel():void{
	PopUpManager.removePopUp(this);
}

private function typeSelectionChange():void{
	txtUnitPrice.text = oppProdDetails.PRODUCTS.entry.(@id == cmbProductName.selectedItem.@id).@unitprice;
}

private function loadData():void{
	var params:String = "OPERATION=OPP_PROD_GETDETAILS" +
						"&PKID=" + escape(StringUtil.trim(this.key)) +
						"&OPPORTUNITYGUID=" + escape(this.opportunityGUID);

	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForOppProdDetails);
	ws.addPartnerServiceFaultEventListener(partnerServiceFaultHandler);
	ws.processServiceRequest(params);
	
//	BusySpinner.getInstance().play(Application.application.ModuleCvs);
}

private function callForOppProdDetails(event:ProcessServiceRequestResultEvent):void{
//	BusySpinner.getInstance().stop();	
	oppProdDetails = XML(event.result);
//	Alert.show(cntctdetails.toString());
	if(oppProdDetails.RESPONSE.RESULT == "E"){
		Alert.show(oppProdDetails.RESPONSE.MESSAGE);
	}else if(oppProdDetails.RESPONSE.RESULT == 'S'){
		setDataOnControls(oppProdDetails);
	}
//	else{
//		Alert.show("Unknow Error: Unable to load response");
//	}
}


private function partnerServiceFaultHandler(event:FaultEvent):void{
//	BusySpinner.getInstance().stop();
	Alert.show(event.fault.toString());
}

private function setDataOnControls(response:XML):void{

	cmbProductName.dataProvider = new XML(response.PRODUCTS).entry as XMLList;
	cmbProductName.selectedIndex = 0;
	cmbProductName.selectedItem = response.PRODUCTS.entry.(@id==response.PRODUCTID)[0] as XML;

	txtUnitPrice.text = oppProdDetails.PRODUCTS.entry.(@id == cmbProductName.selectedItem.@id).@unitprice;
	
	CommonClass.setDataOnComponents(this.txtCustomPrice, response);
	CommonClass.setDataOnComponents(this.txtQuantity, response);
	
	this.cmbProductName.enabled = (this.cmbProductName.selectedIndex == 0);
	
}

private function getPostData():String{
	var postData:String = new String();

	postData += "OPPORTUNITYPRODID=" + (oppProdDetails.OPPORTUNITYPRODID.toString())	+ "&";
	postData += "OPPORTUNITYGUID=" + (oppProdDetails.OPPORTUNITYGUID.toString())		+ "&";
	
	postData += (CommonClass.preparePostString(this.cmbProductName))					+ "&";
	postData += (CommonClass.preparePostString(this.txtQuantity))						+ "&";
	postData += (CommonClass.preparePostString(this.txtCustomPrice));
	return postData;	
}

private function handleSave():void{
	//TODO: Save Operation

	if(validate()){
		if( Number(this.txtQuantity.text) == 0 ){
			confirmAndSave();
		}else{
			saveData("",getPostData());
		}
	}
}

private function validate():Boolean{

	var v:Array = new Array();
	v.push(productV,customPriceV,quantityV);
	
	var result:Array = Validator.validateAll(v);

	if(result.length>0){
		var vWin:ValidationErrorWin = new ValidationErrorWin();
		vWin.Messages = result;
		vWin.title = "Save : Opportunity Product";
		
		PopUpManager.addPopUp(vWin,this,true);
		PopUpManager.centerPopUp(vWin);
		return false;
	}
	return true;
}

private function confirmAndSave():void{
	var a:Alert = Alert.show("Quantity = 0 will remove the product from the opportunity.\n " + 
							"Click OK to continue",
							"Confirm Delete",Alert.OK|Alert.CANCEL,this,confirmHandler);
}
private function confirmHandler(event:CloseEvent):void{
	if(event.detail == Alert.OK){
		saveData("",getPostData());
	}
}
private function saveData(action:String, data:String=""):void{
	var params:String = "OPERATION=OPP_PROD_UPDATEDETAILS" +
						(data.length>0?"&":"") +data;

	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForUpdateOppProductsDetails);
	ws.processServiceRequest(params);
	
//	BusySpinner.getInstance().play(Application.application.CMDWindow);
}


private function callForUpdateOppProductsDetails(event:ProcessServiceRequestResultEvent):void{
	
	var response:XML = XML(event.result);
//	BusySpinner.getInstance().stop();
	
	if(response.RESPONSE.RESULT == "S"){
		if(_caller != null){
			(_caller as OpportunityDetail).reloadOpportunityProducts();
		}
		onClick('cancel');
	}else{
		Alert.show( String(response.RESPONSE.MESSAGE), "Save Error" );	
	}	
}
